package itsm.isperp.report.paser;

import itsm.isperp.framework.data.dialect.DialectFactory;
import itsm.isperp.module.entity.kpi.KpiSetting;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDate;
import org.springframework.data.jdbc.support.DatabaseType;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2015-9-6
 * @since 1.0
 * 
 */
public class QueryLinePaser {

	public static QueryLineLegend paser(KpiSetting setting, String dtype,
			StringBuilder whereSql, Date startDate, Date endDate,
			boolean queryLine) {
		QueryLineLegend d = null;

		if ("month".equals(dtype)) {

			d = QueryLineByMonthPaser.paser(startDate, endDate, queryLine);

		} else if ("week".equals(dtype)) {
			d = QueryLineByWeekPaser.paser(new LocalDate(startDate),
					new LocalDate(endDate), queryLine);

		} else if ("day".equals(dtype)) {
			d = QueryLineByDayPaser.paser(startDate, endDate, queryLine);

		}

		if (queryLine) {

			if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {
				whereSql.append("  AND (" + setting.getQueryDateColumn()
						+ "  BETWEEN to_date('" + d.getStart()
						+ "','yyyy-MM-dd') AND  to_date('" + d.getEnd()
						+ " 23:59','yyyy-MM-dd hh24:mi')) ");
			} else {
				whereSql.append("  AND (" + setting.getQueryDateColumn()
						+ "  BETWEEN '" + d.getStart() + "'  AND  '"
						+ d.getEnd() + " 23:59') ");
			}
		} else {

			if (DialectFactory.getDatabaseType() == DatabaseType.ORACLE) {
				whereSql.append("  AND (" + setting.getQueryDateColumn()
						+ "  BETWEEN to_date('" + d.getStart()
						+ "','yyyy-MM-dd') AND  to_date('" + d.getEnd()
						+ " 23:59','yyyy-MM-dd hh24:mi')) ");
			} else {
				whereSql.append("  AND (" + setting.getQueryDateColumn()
						+ "  BETWEEN '" + d.getStart() + "'  AND  '"
						+ d.getEnd() + " 23:59') ");
			}
		}

		if (StringUtils.isNoneBlank(setting.getQueryWhere())) {
			whereSql.append("   AND " + setting.getQueryWhere());
		}

		return d;
	}
}
